package com.ding.commander;

import com.ding.common.Message;

import java.util.ArrayList;
import java.util.List;

/*
    将心跳检测的功能放在这里处理
 */
public class CoexistCommanderChannel extends CommanderChannel {

    //使用map进行处理
    private List<CommanderChannel> commanderChannels = new ArrayList<>();

    //使用一个轮询指针
    private int current = 0;

    CoexistCommanderChannel() {
        super(null);
    }

    //添加一个
    void addCommanderChannel(CommanderChannel commanderChannel) {
        //变换关闭策略
        commanderChannel.setAfterCloseStrategy(() -> {
            commanderChannels.remove(commanderChannel);
            this.getPool().closeAndRemoveByIntroducerId(this.getId());
        });
        commanderChannel.setPool(this.getPool());
        commanderChannels.add(commanderChannel);
    }

    private CommanderChannel getOne() {

        if (commanderChannels.size() == 0) {
            return null;
        }

        CommanderChannel channel = commanderChannels.get(current);

        current = (current + 1) % commanderChannels.size();

        return channel;
    }

    @Override
    public void sendMsg(Message message) {
        CommanderChannel channel = getOne();
        if (channel != null) {
            channel.sendMsg(message);
        }
    }

    @Override
    public void close() {//关闭的时候轮询关闭所有
        for (CommanderChannel channel : commanderChannels) {
            channel.close();
        }
    }
}
